#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# 重置Python模块缓存
import sys
if 'config' in sys.modules:
    del sys.modules['config']
if 'models.sleep_monitoring' in sys.modules:
    del sys.modules['models.sleep_monitoring']
if 'models.base' in sys.modules:
    del sys.modules['models.base']

# 重新导入
from config import Config, get_database, reset_database
from models.sleep_monitoring import SleepMonitoringRecord, Room

def test_mysql_connection():
    """测试MySQL连接"""
    print("🚀 重置并测试MySQL连接...")
    print(f"📊 配置信息:")
    print(f"   DB_HOST: {Config.DB_HOST}")
    print(f"   DB_PORT: {Config.DB_PORT}")
    print(f"   DB_NAME: {Config.DB_NAME}")
    print(f"   DB_USER: {Config.DB_USER}")
    print()
    
    try:
        # 重置数据库连接
        reset_database()
        print("✅ 数据库连接已重置")
        
        # 获取新的数据库连接
        db = get_database()
        print(f"✅ 数据库对象类型: {type(db)}")
        print(f"✅ 数据库名称: {db.database}")
        
        # 获取连接参数（MySQLDatabase的属性访问方式不同）
        connect_params = db.connect_params
        print(f"✅ 数据库主机: {connect_params.get('host', 'N/A')}:{connect_params.get('port', 'N/A')}")
        print(f"✅ 数据库用户: {connect_params.get('user', 'N/A')}")
        
        # 连接数据库
        db.connect()
        print("✅ 数据库连接成功")
        
        # 检查表是否存在
        room_exists = Room.table_exists()
        record_exists = SleepMonitoringRecord.table_exists()
        print(f"✅ Room表存在: {room_exists}")
        print(f"✅ SleepMonitoringRecord表存在: {record_exists}")
        
        # 如果表不存在，创建它们
        if not room_exists:
            Room.create_table()
            print("✅ Room表已创建")
        
        if not record_exists:
            SleepMonitoringRecord.create_table()
            print("✅ SleepMonitoringRecord表已创建")
        
        # 检查记录数
        if record_exists or not record_exists:  # 重新检查
            try:
                count = SleepMonitoringRecord.select().count()
                print(f"✅ SleepMonitoringRecord记录数: {count}")
                
                if count > 0:
                    records = list(SleepMonitoringRecord.select().order_by(SleepMonitoringRecord.created_at.desc()).limit(1))
                    if records:
                        r = records[0]
                        print(f"✅ 最新记录: 会话ID={r.session_id[:8]}..., 房间={r.room_id}")
            except Exception as e:
                print(f"⚠️  查询记录时出错: {e}")
        
        db.close()
        print("✅ 数据库连接已关闭")
        
        return True
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        return False

def main():
    """主函数"""
    success = test_mysql_connection()
    
    if success:
        print("\n🎉 MySQL数据库连接测试成功！")
        print("现在应用程序将使用MySQL数据库。")
    else:
        print("\n❌ MySQL数据库连接测试失败！")
        print("请检查MySQL服务是否运行，以及配置是否正确。")

if __name__ == '__main__':
    main()